const createGetter = () => {
  return function (target, key, receiver) {
    let res = Reflect.get(target, key, receiver);
    track(target, "get", key);
    return res;
  };
};
const createSetter = () => {
  return function (target, key, value, receiver) {
    let res = Reflect.set(target, key, value, receiver);
    trigger(target, "set", key);
    return res;
  };
};

let activiteEffect = null;

export const effect = (fn, options = {}) => {
  const effectFn = () => {
    try {
      activiteEffect = fn;
      return fn();
    } finally {
      activiteEffect = null;
    }
  };
  if (!options.lazy) {
    effectFn();
  }

  effectFn.scheduler = options.scheduler;
  return effectFn;
};
let trackMap = new Map();
export const track = (target, type, key) => {
  let depsMap = trackMap.get(target);
  if (!depsMap) {
    trackMap.set(target, (depsMap = new Map()));
  }
  let keyDepsMap = depsMap.get(key);
  if (!keyDepsMap) {
    keyDepsMap = new Set();
  }
  if (activiteEffect && !keyDepsMap.has(activiteEffect)) {
    keyDepsMap.add(activiteEffect);
  }
  depsMap.set(key, keyDepsMap);
  console.log("track==trackMap==", trackMap);
  console.log("track==depsMap==", depsMap);
};
export const trigger = (target, type, key) => {
  let depsMap = trackMap.get(target);
  if (!depsMap) {
    return;
  }
  let keyDepsMap = depsMap.get(key);
  if (!keyDepsMap) {
    return;
  }
  keyDepsMap.forEach((effectFn) => {
    if (effectFn.scheduler) {
      effectFn.scheduler();
    } else {
      effectFn();
    }
  });
};

export const mutableHandles = {
  get: createGetter(),
  set: createSetter(),
};
